/*
 * @Description: 角色信息
 * @Author: DHL
 * @Date: 2022-03-30 13:50:53
 * @LastEditors: DHL
 * @LastEditTime: 2022-10-17 09:50:34
 */

import { defineComponent, computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { RoleModel } from '/@/api/system/model/roleModel'
import { apiRoleSave, apiRoleUpdateById } from '/@/api/system/role'
import { log } from '/@/utils/log'
import { apiOrganizationSearchTree } from '/@/api/system/organization'
import { arrayLastValue, listToTree } from '/@/utils/twUtils'

export default defineComponent({
  name: 'RoleForm',
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    /**
     * 公共
     */
    const myData = reactive({
      orgId: '',
      orgName: ''
    })

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      id: '', // 编号
      tenantId: '', // 租户ID
      orgId: '', // 机构编码
      name: '', // 角色名称
      roleType: '4', // 角色类型[ROLE_TYPE](1-超级管理员，2-系统管理员，3-管理员，4-经办人员)
      status: '1', // 角色状态(0:无效；1：有效)
      iconCls: '', // 角色图标
      roleSeq: 1, // 顺序
      description: '' // 角色描述
    }

    let dbForm = reactive<RoleModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      orgId: [
        {
          required: true,
          message: '请选择机构',
          trigger: 'blur'
        }
      ],
      name: [
        {
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        },
        {
          max: 100,
          message: '最多可输入100个字符',
          trigger: 'blur'
        }
      ],
      roleType: [
        {
          required: true,
          message: '请选择角色类型',
          trigger: 'blur'
        }
      ],
      status: [
        {
          required: true,
          message: '请选择角色状态',
          trigger: 'blur'
        }
      ],
      roleSeq: [
        {
          required: false,
          message: '请输入顺序',
          trigger: 'blur'
        }
      ],
      description: [
        {
          max: 200,
          message: '最多可输入200个字符',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(
      actionParam: string,
      rowParam?: RoleModel,
      orgParams?: { orgId: string; orgName: string }
    ) {
      visible.value = true
      loading.value = false
      action.value = actionParam

      handleSearchOrgTree()

      if (['edit', 'view'].indexOf(actionParam) > -1 && rowParam) {
        assign(myData, { orgId: rowParam.orgId })

        assign(dbForm, cloneDeep(rowParam))
      } else {
        assign(myData, orgParams)
        assign(dbForm, orgParams)
      }
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('角色管理', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiRoleSave(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset(!isContinue)
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiRoleUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset(true)
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset(isClosed: boolean) {
      assign(dbForm, cloneDeep(defaultForm))
      if (isClosed) {
        emit('refreshTableData')
        visible.value = false
      }
    }

    //////////////////////////////////////////////////
    // 机构
    //////////////////////////////////////////////////
    const orgTreeData = ref()

    /**
     * 查询机构数据
     */
    function handleSearchOrgTree() {
      apiOrganizationSearchTree().then((result) => {
        if (result?.success) {
          orgTreeData.value = listToTree(result?.data ? result.data : [], 'id', 'parentOrgId', '')
        }
      })
    }

    /**
     * 机构改变事件
     * @param value
     */
    function handleChangeOrg(value: Array<string>) {
      dbForm.orgId = arrayLastValue(value)

      dbFormRef.value.validateField('orgId')
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      myData,
      dbFormRef,
      dbForm,
      rules,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset,
      orgTreeData,
      handleChangeOrg
    }
  }
})
